const mysql = require('mysql');
const baseTool = require('../../common/base-tool');

class DataHanderClass {
    constructor() {
    }

    /**
     * 封装查询条件
     * @param rows Object
     * @param field String
     * @param value String
     * @returns {Array}
     *
     * Example: dataHander.whereOr(orderRows, 'id', 'pid');
     */
    whereOr ( rows, field, value ) {
        let where = [];
        let tmp = '';
        where.push({or: 1});
        for (let i in rows) {
            tmp = {
                wfield: field,
                wvalue: rows[i][value]
            }
            where.push(tmp);
        }
        return where;
    }

    /**
     * escape编码，防sql注入
     * @param w {}
     * @returns {string}
     */
    noInjection(w) {
        let whe = '';
        if (w[0].or) {
            // or条件
            for (let i in w) {
                if(w[i].wfield) whe += `\`${w[i].wfield}\`=${mysql.escape(w[i].wvalue)} or  `
            }
        } else {
            // and条件
            for (let i in w) {
                whe += `\`${w[i].wfield}\`=${mysql.escape(w[i].wvalue)} and `
            }
        }
        return whe.substr(0, whe.length - 5);
    }

    /**
     * 处理插入数据
     * @param sql {}
     * @returns {f: string, v: string}
     */
    initField(sql) {
        let f = '';
        let v = '';
        let tempField = sql.fields.split(',');
        let tempValues = sql.values.split(',');

        for (let i in tempField) {
            if (tempField[i] && tempValues[i]) {
                f += `\`${baseTool.trim(tempField[i])}\`,`;
                v += `'${baseTool.trim(tempValues[i])}',`;
            }
        }

        f = f.substr(0, f.length - 1);
        v = v.substr(0, v.length - 1);
        return {f: f, v: v};
    }
}

module.exports = new DataHanderClass();